package com.huawei.M01.iterator;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class DESDemo {
    public static void main(String[] args) throws NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException {
        // 需要加密的内容
        String input = "itbaizhan";
        // 私钥
        String key = "15431324";
        // 协议
        String algorithm = "DES";

        String coder = enCoder(input, algorithm, key); // NNfWhuQ5raWXixqfKxNThA==
        System.out.println(coder);

        String s = deCoder(coder, algorithm, key);
        System.out.println(s);
    }

    private static String deCoder(String input, String algorithm, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 1.获取加密方式
        Cipher cipher = Cipher.getInstance(algorithm);
        // 2.
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);

        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        // jieMi
        byte[] decode = Base64.getDecoder().decode(input);

        byte[] bytes = cipher.doFinal(decode);

        return new String(bytes);

    }

    private static String enCoder(String input, String algorithm, String key) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {

        // 获取加密算法
        Cipher cipher = Cipher.getInstance(algorithm);
        // 创建加密规则
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);

        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] bytes = cipher.doFinal(input.getBytes());

        return new String(Base64.getEncoder().encode(bytes));
    }
}
